<?php
// +----------------------------------------------------------------------
// | Description: 合同
// +----------------------------------------------------------------------
// | Author:  Michael_xu | gengxiaoxu@5kcrm.com
// +----------------------------------------------------------------------
namespace app\crm\model;

use app\admin\model\Record;
use app\admin\model\User;
use think\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;

class Personnel extends Common
{
    protected $name = 'crm_accounting';
    protected $createTime = 'createtime';
    protected $updateTime = '';
    protected $autoWriteTimestamp = true;
    private $statusArr = ['0' => '待接收', '1' => '未完结', '2' => '已完结'];
    /**
     * [getDataList 外勤list]
     * @author Michael_xu
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */
    public function getDataList($request)
    {
        $user_id = $request['user_id'];
        $where=[];
        if($request["butler_time"]){
            $butler_time=$request["butler_time"];
            $where["assignfield.butler_time"]=["between",[$butler_time["start"],$butler_time["end"]]];
        }
        if($request["ok_time"]){
            $butler_time=$request["ok_time"];
            $where["assignfield.ok_time"]=["between",[$butler_time["start"],$butler_time["end"]]];
        }
        if($request["butler_realname"]){
            $realname=$request["butler_realname"];
            $where["butler.realname"]=["like",'%'.$realname["value"].'%'];
        }
        //办理事项
        if($request["name"]){
            $realname=$request["name"];
            $where["assignfield.name"]=["like",'%'.$realname["value"].'%'];
        }
        if($request["admin_realname"]){
            $realname=$request["admin_realname"];
            $where["admin.realname"]=["like",'%'.$realname["value"].'%'];
        }
        if($request["contract_name"]){
            $contract_name=$request["contract_name"];
            $where["contract.name"]=["like",'%'.$contract_name["value"].'%'];
        }
        //服务公司名称检索
        if($request["service_name"]){
            $service_name=$request["service_name"];
            $where["contract.name"]=["like",'%'.$service_name["value"].'%'];
        }
        if($request["contract_num"]){
            $contract_num=$request["contract_num"];
            $where["contract.num"]=["like",'%'.$contract_num["value"].'%'];
        }
        if($request["processing"]){
            $contract_num=$request["processing"];
            $where["processing"]=["=",$contract_num["value"]];
        }
        if($request["create_user"]){
            $create_user=$request["create_user"]["value"];
            $where["createdUser.realname"]=$create_user;
        }
        //客户名称进行搜索
        if($request["customer_name"]){
            $customer_name=$request["customer_name"]["value"];
            $where["customer.name"]=$customer_name;
        }
        if($request["status"]){
            $status=$request["status"];
            $status_num=0;
            if($status["value"]=="未完结") $status_num=1;
            if($status["value"]=="已完结") $status_num=2;
            if($status["value"]=="待验收") $status_num=1;
            $is="=";
            if($status["condition"]=="isnot")$is=" <> ";
            $where["assignfield.status"]=[$is,$status_num];
            if($status["value"]=="待验收"){
                $assignfield_id_arr=db('crm_assignfield_recorde')->where(["status"=>1,"state"=>0])->column("assignfield_id");//id
                if($assignfield_id_arr){
                    $where["assignfield.assignfield_id"]=["in",$assignfield_id_arr];
                }
            }
        }
        unset($request["user_id"]);
        $request = $this->fmtRequest( $request );
        $map = $request['map'] ? : [];
        if(empty($map["search"])){
            $map=[];
        }
        if($map["search"]){
            $map["contract.name"]=["like",'%'.$map["search"].'%'];
            unset($map["search"]);
        }
        //$where=["contract_id"=>$request["contract_id"]];
        //列表展示字段
        // $indexField = $fieldModel->getIndexField('crm_contract', $user_id);
        $butler_where=[];
        if (!empty($user_id)) {
            //管家
            $group = db('admin_access')->where(['user_id' => $user_id, "group_id" => "1"])->find();
            if(empty($group)){
                //查找下级订单
                $group_ids = db('admin_access')->where(['user_id' => $user_id])->column('group_id');
                if (!in_array(1, $group_ids) && !in_array(32, $group_ids)) {
                    if (!empty($butler_where)) {
                        $butler_where .= " and ";
                    }
                    $user_ids = User::field("GROUP_CONCAT(id) ids")->where(["parent_id" => $user_id])->find()["ids"];
                    $user_where = " assignfield.admin_user_id =" . $user_id;
                    if (!empty($user_ids)) {
                        $user_where .= " or assignfield.admin_user_id in (" . $user_ids . ")";
                    }
                    $butler_where .= " (" . $user_where . ")";
                }
                //管家
                $group_gj = db('admin_access')->where(['user_id' => $user_id, "group_id" => "32"])->find();
                if (!empty($group_gj)) {
                    // $butler_where = "assignfield.butler_id={$user_id} or admin_user_id={$user_id}";

                }

                $group = db('admin_access')->where(['user_id' => $user_id, "group_id" => "31"])->find();
                if (!empty($group) && empty($group_gj)) {
                    $butler_where = "assignfield.admin_user_id=" . $user_id;
                }
                
            }
        }
        $order = 'assignfield.butler_time desc,assignfield.assignfield_id desc';
        $list = db('crm_assignfield')
            ->alias('assignfield')
            ->join('admin_user admin',"admin.id=assignfield.admin_user_id","left")
            ->join('admin_user butler',"butler.id=assignfield.butler_id","left")
            ->join('__CRM_CONTRACT__ contract',"contract.contract_id=assignfield.contract_id","left")
            ->join('__CRM_CUSTOMER__ customer',"customer.customer_id=contract.customer_id","left")
            ->join('admin_user createdUser',"createdUser.id=contract.create_user_id","left")
            //->join('__CRM_CONTRACT__ contract',"FIND_IN_SET(admin.id,REPLACE(rw_user_id,',',','))")
            ->where($where)
            ->where($butler_where)
            ->where($map)
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->field('assignfield.*
            ,admin.id as admin_id,admin.username admin_username,admin.realname admin_realname
            ,butler.id as butler_id,butler.username butler_username,butler.realname butler_realname
            ,contract.name contract_name,contract.num contract_num,contract.contract_id,customer.name customer_name,createdUser.realname create_user')
            ->order($order)
            ->select();
        $dataCount =  db('crm_assignfield')
            ->alias('assignfield')
            ->join('admin_user admin',"admin.id=assignfield.admin_user_id","left")
            ->join('admin_user butler',"butler.id=assignfield.butler_id","left")
            ->join('__CRM_CONTRACT__ contract',"contract.contract_id=assignfield.contract_id","left")
            ->join('__CRM_CUSTOMER__ customer',"customer.customer_id=contract.customer_id","left")
            ->join('admin_user createdUser',"createdUser.id=contract.create_user_id","left")
            ->where($where)
            ->where($butler_where)
            ->where($map)
            ->count('1');
        $contract_id=[];
        if(!empty($list)){
            foreach ($list as $k=> &$v){
                if($v['butler_time']) {
                   $v['butler_time'] = date('Y-m-d H:i:s',$v['butler_time']); 
                }
                if($v['ok_time']) {
                   $v['ok_time'] = date('Y-m-d H:i:s',$v['ok_time']); 
                }
                
                /*$v["admin"]=[
                    "id"=>$v["admin_id"],
                    "username"=>$v["admin_username"],
                    "realname"=>$v["admin_realname"],
                ];
                $v["butler"]=[
                    "id"=>$v["butler_id"],
                    "username"=>$v["butler_username"],
                    "realname"=>$v["butler_realname"],
                ];*/
                $assignfield_recorde=db('crm_assignfield_recorde')->where(["assignfield_id"=>$v["assignfield_id"],"state"=>0])->find();//查看是否有待审核的完结记录
                $list[$k]['status'] = $assignfield_recorde?"待验收":$this->statusArr[$v['status']];
                if(empty($v["processing"]) && !empty($v["receive_time"]) && $v["status"]==2){
                    //计算办件时间
                    $processing=abs($v["ok_time"]-$v["receive_time"]);//办件时间；
                    $processing=ceil($processing/86400);
                    $list[$k]['processing']=$processing?:0;
                }
            }
        }
        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ? : 0;
        $productCount=0;
        $documentsCount=0;
//        $commissionPrice=0;
        $contract_id = db('crm_assignfield')
        ->alias('assignfield')
        ->field("GROUP_CONCAT(DISTINCT assignfield.assignfield_id) assignfield_id,GROUP_CONCAT(DISTINCT assignfield.contract_id) contract_id")
        ->join('admin_user admin',"admin.id=assignfield.admin_user_id","left")
        ->join('admin_user butler',"butler.id=assignfield.butler_id","left")
        ->join('__CRM_CONTRACT__ contract',"contract.contract_id=assignfield.contract_id","left")
        ->join('__CRM_CUSTOMER__ customer',"customer.customer_id=contract.customer_id","left")
        ->join('admin_user createdUser',"createdUser.id=contract.create_user_id","left")
        ->where($where)
        ->where($butler_where)
        ->where($map)
        ->find();
        if(!empty($contract_id)){
            $productCount= strlen($contract_id["contract_id"]);
            /*$documentsCount=db('crm_assignfield_recorde')->whereIn("contract_id",$contract_id)
                ->where(["state"=>"1"])->where($where)->count();*///->where($where)
//            $commissionPrice=Assignfield::whereIn("assignfield_id",$contract_id["assignfield_id"])->sum("money");
        }
        //获取提成金额
        $commissionPrice =  db('crm_assignfield')
            ->alias('assignfield')
            ->join('admin_user admin',"admin.id=assignfield.admin_user_id","left")
            ->join('admin_user butler',"butler.id=assignfield.butler_id","left")
            ->join('__CRM_CONTRACT__ contract',"contract.contract_id=assignfield.contract_id","left")
            ->join('__CRM_CUSTOMER__ customer',"customer.customer_id=contract.customer_id","left")
            ->join('admin_user createdUser',"createdUser.id=contract.create_user_id","left")
            ->where($where)
            ->where($butler_where)
            ->where($map)
            ->sum('assignfield.money');
        $count['productCount'] = $productCount ? : 0;//产品总数量
        $count['documentsCount'] = $dataCount ? : 0;//总办件数量
        $count['commissionPrice'] = $commissionPrice ? : 0;//总提成金额
        $data['data']=$count;
        /*$data['data']['sumMoney'] = $sumMoney ? : 0.00;
        $data['data']['unReceivablesMoney'] = $unReceivablesMoney ? : 0.00;*/
        return $data;
    }
    /**
     * [getFlowList 外勤跟进记录list]
     * @author Michael_xu
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */
    public function getFlowList($request)
    {
        $where=["assignfield_recorde.contract_id"=>$request["contract_id"]];
        if(!empty($request["user_id"])){
            $where["admin_user_id"]=$request["user_id"];
        }
        $order = 'assignfield_recorde.createtime desc,assignfield_recorde.assignfield_recorde_id desc';
        $list = db('crm_assignfield_recorde')
            ->alias('assignfield_recorde')
            ->join('admin_user admin',"admin.id=assignfield_recorde.admin_user_id","left")
            //->join('admin_user butler',"butler.id=assignfield.butler_id","left")
            ->join('__CRM_CONTRACT__ contract',"contract.contract_id=assignfield_recorde.contract_id","left")
            ->where($where)
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->field('assignfield_recorde.*,from_unixtime(createtime, \'%Y-%m-%d %H:%i:%s\') createtime
            ,admin.id as admin_id,admin.username admin_username,admin.realname admin_realname
            ,contract.name contract_name,contract.num contract_num,contract.contract_id')
            ->order($order)
            ->select();
        $dataCount =  db('crm_assignfield_recorde')
            ->alias('assignfield_recorde')
            ->join('admin_user admin',"admin.id=assignfield_recorde.admin_user_id","left")
            //->join('admin_user butler',"butler.id=assignfield.butler_id","left")
            ->join('__CRM_CONTRACT__ contract',"contract.contract_id=assignfield_recorde.contract_id","left")
            ->where($where)
            ->count('1');
        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ? : 0;
        return $data;
    }
    /**
     * [getpersonnel 合同分配外勤list]
     * @author Michael_xu
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */
    public function getpersonnel($request)
    {
        $where=["contract_id"=>$request["contract_id"],"status"=>2];
        if(isset($request["user_id"]) && !empty($request["user_id"])){
            $where["assignfield.admin_user_id"]=$request["user_id"];
        }
        $order = 'assignfield.butler_time desc,assignfield.assignfield_id desc';
        $list = db('crm_assignfield')
            ->alias('assignfield')
            ->join('admin_user admin',"admin.id=assignfield.admin_user_id","left")
            //->join('admin_user butler',"butler.id=assignfield.butler_id","left")
            ->join('__CRM_CONTRACT__ contract',"contract.contract_id=assignfield.contract_id","left")
            ->where($where)
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->field('assignfield_recorde.*
            ,admin.id as admin_id,admin.username admin_username,admin.realname admin_realname
            ,contract.name contract_name,contract.num contract_num,contract.contract_id')
            ->order($order)
            ->select();
        $dataCount =  db('crm_assignfield_recorde')
            ->alias('assignfield_recorde')
            ->join('admin_user admin',"admin.id=assignfield.admin_user_id","left")
            //->join('admin_user butler',"butler.id=assignfield.butler_id","left")
            ->join('__CRM_CONTRACT__ contract',"contract.contract_id=assignfield_recorde.contract_id","left")
            ->where($where)
            ->count('1');
        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ? : 0;
        return $data;
    }

}